package com.drore.cloud.controller;

import com.drore.cloud.constant.LocalConstant;
import com.drore.cloud.domain.sys.RestMessage;
import com.drore.cloud.exception.ApiException;
import com.drore.cloud.jdbc.MultiDS;
import com.drore.cloud.sdkjdbc.core.JdbcRunner;
import com.drore.cloud.sdkjdbc.model.Pagination;
import com.drore.cloud.utils.DSUtil;
import com.drore.cloud.utils.GsonUtil;
import com.drore.cloud.utils.MapClearUtil;
import com.drore.cloud.utils.ThreadLocalHolder;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/***
 * 浙江卓锐科技股份有限公司 版权所有@Copyright 2016
 * 说明  新增数据源
 * 项目名称
 * @since:cloud-ims 1.0
 * @author <a href="mailto:baoec@drore.com">baoec@drore.com </a> 
 * 2018/07/10 16:28
 */
@Api("数据库模块")
@RequestMapping(value = "/dbm/data_source")
@RestController
public class dataSourceCtl {
    @Autowired
    private JdbcRunner run;

    @Autowired
    private MultiDS mult;

    @ApiOperation("数据库连接测试")
    @RequestMapping(value = "/test" ,method = {RequestMethod.POST, RequestMethod.GET})
    public RestMessage test(String username, String password, String driver_class_name,String url)  {
        RestMessage rm=new RestMessage();

        BasicDataSource ds = new BasicDataSource();
        ds.setDriverClassName(driver_class_name);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        JdbcRunner jdbc = new JdbcRunner();
        jdbc.setDataSource(ds);
        boolean b;
        try {
             b = jdbc.connectionTest();
        } catch (SQLException e) {
            throw new ApiException("数据库连接失败:"+e.getLocalizedMessage());
        }
        rm.setSuccess(b);
        rm.setData("数据库连接成功");
        return rm;
    }

    @ApiOperation("数据库发布")
    @RequestMapping(value = "/issue" ,method = {RequestMethod.POST, RequestMethod.GET})
    public RestMessage issue(String id)  {
        RestMessage rm=new RestMessage();
        //数据库信息
        Map<String, Object> data_source_info = run.queryOne("data_source_info", id);
        String instance_id = Objects.toString(data_source_info.get("instance_id"));
        //数据实例信息
        Map<String, Object> db_instance_info = run.queryOne("db_instance_info", instance_id);
        //配置数据源
        BasicDataSource ds = DSUtil.newBDS(db_instance_info);
        JdbcRunner jdbc = new JdbcRunner();
        jdbc.setDataSource(ds);
        //3将 获得的信息  组装成  建表语句
        String create_database_sql=" CREATE  database " +data_source_info.get("prefix_name")+";";
        boolean b;
        BasicDataSource dataSourcenew;
        try {
            b = jdbc.executSql(create_database_sql);
            //添加到系统中 立即可以使用
             jdbc.getDataSource().close();

        } catch (SQLException e) {
            throw new ApiException("数据库创建失败:"+e.getLocalizedMessage());
        }
        rm.setSuccess(b);
        rm.setData("数据库创建成功");
        //创建成功后 修改资源的发布状态
        run.update("data_source_info",ImmutableMap.of("id",id,"status","issued"));

        db_instance_info.put("url",Objects.toString(db_instance_info.get("url"))+"/"+Objects.toString(data_source_info.get("prefix_name")));
        //将新建的数据库 配置到系统中
        BasicDataSource dsnew = DSUtil.newBDS(db_instance_info);
        JdbcRunner jdbcnew = new JdbcRunner();
        jdbcnew.setDataSource(dsnew);
        mult.addDS(Objects.toString(data_source_info.get("id")),jdbcnew);
        return rm;
    }

    @RequestMapping(value = "/save" ,method = {RequestMethod.POST, RequestMethod.GET})
    public RestMessage save(String resource_name, String submit_data)  {
        RestMessage rm=new RestMessage();
        Gson gson = GsonUtil.create();
        Map<String, Object> map = (Map<String,Object>)gson.fromJson(submit_data, Map.class);
        if(map.get("file")!=null){
            map.remove("file");
        }
        String insert=null;
        map= MapClearUtil.clear(map);

        map.put("status","wait_issue");
        String prefix_name = Objects.toString(map.get("prefix_name"));
        Pagination pagination = run.queryListByExample("data_source_info", ImmutableMap.of("prefix_name", prefix_name));
        if(pagination.getCount()>0){
            throw new ApiException("该数据库前缀已被占用,请更换。");
        }

        //关联数据库类型
        if(map.get("id")==null){
            insert=run.insert(resource_name,map);

        }else {
            insert=run.update(resource_name,map);
        }
        BasicDataSource ds = new BasicDataSource();
        ds.setDriverClassName(Objects.toString(map.get("driver_class_name")));
        ds.setUrl(Objects.toString(map.get("url")));
        if (map.get("username")!=null){
            ds.setUsername(Objects.toString(map.get("username")));
        }
        if (map.get("password")!=null){
            ds.setPassword(Objects.toString(map.get("password")));
        }
        JdbcRunner jdbc = new JdbcRunner();
        jdbc.setDataSource(ds);
        mult.addDS(Objects.toString(insert),jdbc);
        rm.setData(insert);
        return rm;
    }

    @ApiOperation("我的连接信息")
    @RequestMapping(value = "/my" ,method = {RequestMethod.POST, RequestMethod.GET})
    public Pagination my(String resource_name, String submit_data)  {
        RestMessage rm=new RestMessage();
        Map<String, Object> sys_user_info = (Map<String, Object>) ThreadLocalHolder.getCurrentUser();
        Map<String, Object> data_source_info = run.queryOne("data_source_info", Objects.toString(sys_user_info.get("data_source_id")));
        Map<String, Object> db_instance_info = run.queryOne("db_instance_info", Objects.toString(data_source_info.get("instance_id")));


        HashMap<String, Object> developer_url = Maps.newHashMap();
        //开发者账号
        developer_url.put("appid",Objects.toString(sys_user_info.get("appid")));
        //开发者密码
        developer_url.put("appscrect",Objects.toString(sys_user_info.get("appscrect")));
        //数据库url
        developer_url.put("url",Objects.toString(db_instance_info.get("url")));
        //数据库名称
        developer_url.put("prefix_name",Objects.toString(data_source_info.get("prefix_name")));
        //数据库类型
        developer_url.put("data_type",Objects.toString(db_instance_info.get("data_type")));
        //数据库classname
        developer_url.put("driver_class_name",Objects.toString(db_instance_info.get("driver_class_name")));

        ArrayList<Object> objects = Lists.newArrayList();
        objects.add(developer_url);
        Pagination pagination = new Pagination();
        pagination.setCurrent_page(1);//当前第几页
        pagination.setCount(1);//总条数
        pagination.setTotal_page(1);//总页数
        pagination.setPage_size(1);//每页有几条
        pagination.setData(objects);
        return pagination;
    }
}
